<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>异步遍历的接口</title>
</head>
<body>
    <h1>异步遍历的接口</h1>

    <script>
        // 异步遍历器的接口
        class AsyncIterator {
            constructor(array) {
                this.array = array;
                this.index = 0;
            }

            [Symbol.asyncIterator]() {
                return {
                    array: this.array,
                    index: this.index,
                    async next() {
                        if (this.index < this.array.length) {
                            const value = await this.array[this.index++];
                            return { value, done: false };
                        }
                        return { value: undefined, done: true };
                    }
                };
            }
        }

        // 使用异步遍历器
        const promises = [
            Promise.resolve(1),
            Promise.resolve(2),
            Promise.resolve(3)
        ];

        const asyncIter = new AsyncIterator(promises);

        // 手动遍历
        async function manualIteration() {
            const iterator = asyncIter[Symbol.asyncIterator]();
            console.log(await iterator.next()); // { value: 1, done: false }
            console.log(await iterator.next()); // { value: 2, done: false }
            console.log(await iterator.next()); // { value: 3, done: false }
            console.log(await iterator.next()); // { value: undefined, done: true }
        }

        // 实际应用示例：异步文件读取器
        class AsyncFileReader {
            constructor(files) {
                this.files = files;
            }

            [Symbol.asyncIterator]() {
                let index = 0;
                const files = this.files;

                return {
                    async next() {
                        if (index < files.length) {
                            const file = files[index++];
                            const content = await new Promise(resolve => {
                                setTimeout(() => {
                                    resolve(`文件${file}的内容`);
                                }, 1000);
                            });
                            return { value: content, done: false };
                        }
                        return { value: undefined, done: true };
                    }
                };
            }
        }

        const fileReader = new AsyncFileReader(['a.txt', 'b.txt', 'c.txt']);
        
        // 使用for await...of遍历
        async function readFiles() {
            for await (const content of fileReader) {
                console.log(content);
            }
        }

        readFiles();
    </script>
</body>
</html> 